<?php


namespace app\model;

use think\Model;

class ScreenCategory extends Model
{
	protected $table = 'screen_category';
	protected $strict = false;
	/**
	 * 生成菜单下拉框option
	 * @param array $data
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function listOptions($type = 1)
	{
		$data = $this->where('type',$type)->select();
		$menusList = $this->getTreeLevel($data);
		foreach ($menusList as &$value) {
			$value['label'] = str_repeat("　├　", $value['level'] + 1) . $value['name'];
		}
		return $menusList;
	}

	protected function getTreeLevel($array, $pid = 0, $level = 0)
	{
		//声明静态数组,避免递归调用时,多次声明导致数组覆盖
		static $listMenus = [];
		foreach ($array as $key => $value) {
			//第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
			if ($value['pid'] == $pid) {
				//父节点为根节点的节点,级别为0，也就是第一级
				$value['level'] = $level;
				//把数组放到list中
				$listMenus[] = $value;
				//把这个节点从数组中移除,减少后续递归消耗
				unset($array[$key]);
				//开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
				$this->getTreeLevel($array, $value['id'], $level + 1);
			}
		}
		return $listMenus;
	}
}
